class Molecule < ActiveRecord::Base

  def self.search(query)
    case query
    when /\AC\d+\z/
      Molecule.search_by_kegg_id(query)
    when /\A\d+[.,]?\d*\z/
      Molecule.search_by_mass(query.to_f)
    when /\A([A-Z][a-z]?\d*)+\z/
      Molecule.search_by_formula(query)
    else
      Molecule.search_by_name(query)
    end
  end

  def self.search_by_formula(formula)
    Molecule.find(:all, :conditions => ["formula ILIKE ?", "#{formula}%"],
                  :limit => 10, :order => :formula)
  end

  def self.search_by_kegg_id(kegg_id)
    Molecule.find(:all, :conditions => ["compound ILIKE ?", "#{kegg_id}%"],
                  :limit => 10, :order => :compound)
  end

  def self.search_by_name(name)
    Molecule.find(:all, :conditions => ["names ILIKE ?", "%#{name}%"],
                  :limit => 10, :order => :names)
  end

  def self.search_by_mass(mass)
    number_of_decimals = mass.to_s.split(".")[1].size rescue 0
    epsilon = 10 ** -number_of_decimals
    Molecule.find(:all, :conditions => ["mass > ? AND mass < ? ",
                                        mass - epsilon, mass + epsilon],
                  :limit => 10, :order => :mass)
  end
end
